﻿using System;
using System.Device.Location;
using GalaSoft.MvvmLight.Threading;
using Microsoft.Phone.Maps.Controls;
using Microsoft.WindowsAzure.MobileServices;
using SkiTracker.Model;
using Windows.Devices.Geolocation;


namespace SkiTracker.ViewModel
{
    public class ReadMessageViewModel : MapViewModel
    {

        private readonly IMobileServiceTable<Message> _messageTable = App.MobileService.GetTable<Message>();

        public ReadMessageViewModel() : this(0)
        {
        }


        public ReadMessageViewModel(int id)
        {
            Id = id;

            if (Id != 0)
                LoadMessage(Id);
            else
            {
                if (App.CurrentApp.CurrentDevice != null)
                    LoadLastMessage();
                else
                    App.CurrentApp.DeviceLoaded += (sender, args) => LoadLastMessage();
            }


            PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == "Message" || args.PropertyName == "CurrentLocation")
                {
                    SetView();
                }
            };

            GetCurrentPosition();

        }

        public int Id { get; private set; }

        private async void LoadLastMessage()
        {
            var device = App.CurrentApp.CurrentDevice;

            var messageQuery = _messageTable.OrderByDescending(m => m.CreatedAt).Where(m => m.GroupName == device.GroupName).Take(1);

            var messages = await messageQuery.ToListAsync();

            if (messages.Count > 0)
            {
                Message = messages[0];
            }

        }
        private async void LoadMessage(int id)
        {
            Message = await _messageTable.LookupAsync(id);
        }


        private Message _message;
        public Message Message
        {
            get { return _message; }
            set
            {
                _message = value;
                RaisePropertyChanged(() => Message);
            }
        }


        protected Geolocator Geolocator;

        protected async void GetCurrentPosition()
        {
            Geolocator = new Geolocator
            {
                DesiredAccuracy = PositionAccuracy.High,
            };

            var geoposition = await Geolocator.GetGeopositionAsync(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15));
            CurrentLocation = new GeoCoordinate(geoposition.Coordinate.Latitude, geoposition.Coordinate.Longitude);

        }

        private GeoCoordinate _currentLocation;
        public virtual GeoCoordinate CurrentLocation
        {
            get { return _currentLocation; }
            set
            {
                _currentLocation = value;

                DispatcherHelper.CheckBeginInvokeOnUI(() => RaisePropertyChanged(() => CurrentLocation));

            }
        }

        private void SetView()
        {
            if (Message != null && Message.Coordinate != null && !Message.Coordinate.IsUnknown
                && CurrentLocation != null)
                Messenger.Send(LocationRectangle.CreateBoundingRectangle(new[] { Message.Coordinate, CurrentLocation }));
            else
            {
                ZoomLevel = 14;

                if (CurrentLocation != null)
                    MapCenter = CurrentLocation;

                else if (Message != null && Message.Coordinate != null && !Message.Coordinate.IsUnknown)
                    MapCenter = Message.Coordinate;

            }
        }


        private GeoCoordinate _mapCenter = new GeoCoordinate(47, 12);
        public GeoCoordinate MapCenter
        {
            get { return _mapCenter; }
            set
            {
                if (_mapCenter != value)
                {
                    _mapCenter = value;
                    RaisePropertyChanged(() => MapCenter);
                }
            }
        }
    }
}
